import React, { useEffect, useState } from 'react';
import {
  View, FlatList, RefreshControl
} from 'react-native';

import { colors } from '../../constants/theme';
import { ProcessItem } from '../../components';
import Http from '../../service/http';
import DataUtil from '../../utils/DataUtil';
import requestCheck from '../../utils/RequestCheckUtil';


export default function Process({ navigation }) {
  const [refresh, setRefresh] = useState(0);
  const [dataSource, setDataSource] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    async function fetchData() {
      setIsLoading(true);
      const res = await Http.inquireHistory();
      const callback = (d) => setDataSource(DataUtil.convertHistory2List(d));
      requestCheck(res, callback, navigation);
      setIsLoading(false);
    }
    fetchData();
  }, [navigation, refresh]);

  const renderItem = (item) => (<ProcessItem item={item} navigation={navigation} key={item.id} />);

  return (
    <View style={{ flex: 1 }}>
      <FlatList
        data={dataSource}
        renderItem={(item) => renderItem(item.item)}
        keyExtractor={(item) => `${item.id}`}
        refreshControl={(
          <RefreshControl
            title="加载中"
            titleColor={colors.secondary}
            colors={[colors.primary, colors.secondary]}
            tintColor={colors.primary}
            refreshing={isLoading}
            onRefresh={() => setRefresh(refresh + 1)}
          />
        )}
      />
    </View>
  );
}
